package net.sureon.web.user;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.UserSession;
import net.sureon.biz.DailyTimingMgr;
import net.sureon.common.SureonConstants;
import net.sureon.dao.DailyTiming;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * 
 * @author Administrator
 * 
 */
public class MyApply implements Controller {
  
	private DailyTimingMgr dailyTimingMgr;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		long userID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getUserID();

		long companyID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getCompanyID();
		
		String showContent = request.getParameter("showContent");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		
		java.util.Date workDate = null;
		
		workDate = sdf.parse(sdf.format(new java.util.Date()));
		
		DailyTiming dt = dailyTimingMgr.getDailyTimingByWorkDate(companyID, userID, workDate);
		
		if(showContent != null && "yes".equals(showContent)) {
			long dailyTimingID = Long.parseLong(request.getParameter("dailyTimingID"));
			DailyTiming dailyTiming = dailyTimingMgr.getDailyTimingByID(companyID, dailyTimingID);
			request.setAttribute("dailyTiming", dailyTiming);
		}
		else{
			if(dt != null) {
				request.setAttribute("allowNewDailyTiming", "false");
			}
		}
		
		String cp = request.getParameter("currentPage");
		int currentPage = 1;
		if(!"".equals(cp)) {
			try {
				currentPage = Integer.parseInt(request.getParameter("currentPage"));
			} catch(Exception e) {
				
			}
		}
		int maxResults = SureonConstants.PAGE_SIZE;
		int skipResults = (currentPage - 1) * maxResults;
		
		
		List<DailyTiming> all = null;
		all = dailyTimingMgr.getDailyTimingByUserNotReview(companyID, userID, skipResults, maxResults);

		request.setAttribute("all", all);
		int pageCounter = (dailyTimingMgr.getDailyTimingByUserNotReview(companyID, userID, 0, 10000).size() + SureonConstants.PAGE_SIZE - 1) / SureonConstants.PAGE_SIZE;
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("pageCounter", pageCounter);
		String errorMsg = request.getParameter("errorMsg");
		if(errorMsg != null) {
			request.setAttribute("errorMsg", errorMsg);	
		}
		return new ModelAndView("user/myApply");
	}

	public DailyTimingMgr getDailyTimingMgr() {
		return dailyTimingMgr;
	}

	public void setDailyTimingMgr(DailyTimingMgr dailyTimingMgr) {
		this.dailyTimingMgr = dailyTimingMgr;
	}
}
